package com.code.common.aop;

import cn.hutool.core.util.StrUtil;
import com.code.common.annotation.Idempotent;
import com.code.common.constant.IdempotentConst;
import com.code.common.exception.ServiceException;
import com.code.common.expression.KeyResolver;
import com.code.common.utils.HelperUtil;
import com.code.common.utils.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: Yan
 * @date: 2023/3/31
 *
 * 对有Idempotent注解的接口请求生成token，用来幂等性判断
 */
@Slf4j
@Aspect
@Component
public class IdempotentAop {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private KeyResolver keyResolver;

    @Pointcut(value = "@annotation(com.code.common.annotation.Idempotent)")
    public void pointcut(){}

    /**
     * 前置通知，方法执行前就会执行
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Before(value = "pointcut()")
    public void doBefore(JoinPoint joinPoint) {
        HttpServletRequest request = HelperUtil.getHttpServletRequest();

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        if (!method.isAnnotationPresent(Idempotent.class)) {
            return;
        }

        Idempotent idempotent = method.getAnnotation(Idempotent.class);

        // 首个请求后面的请求，3秒内不断请求，抛出请勿重复提交异常
        String incrKey = this.setCacheKey(idempotent, joinPoint, IdempotentConst.INCR_KEY_PREFIX);
        Long increment = stringRedisTemplate.opsForValue().increment(incrKey, 1L);
        stringRedisTemplate.expire(incrKey, idempotent.expireTime(), idempotent.timeUnit());

        if (increment > 1) {
            // 续期是为了过来更多请求，超过3秒后导致请求再次出现提交重复数据，但一般不会这么多请求
            stringRedisTemplate.expire(incrKey, idempotent.expireTime(), idempotent.timeUnit());
            throw new ServiceException(idempotent.msg());
        }

        // 没有配置幂等标识 key ，使用请求IP + URL + 请求方法 + 参数列表区分
        String idempotentKey = this.setCacheKey(idempotent, joinPoint, IdempotentConst.CACHE_TOKEN_PREFIX);

        //将token放入redis中，设置有效期为默认3S，不存在key则设置，设置成功返回absent为true
        boolean absent = stringRedisTemplate.opsForValue().setIfAbsent(idempotentKey, "1", idempotent.expireTime(), idempotent.timeUnit());

        if (absent) {
            request.setAttribute(IdempotentConst.REQUEST_REPEAT, 0);
        }else {
            request.setAttribute(IdempotentConst.REQUEST_REPEAT, 1);
        }

    }

    /**
     * 执行顺序：@Around → @Before → @After → @Around执行 ProceedingJoinPoint.proceed() 之后的操作 → @AfterRunning(如果有异常 → @AfterThrowing)
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around(value = "pointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed = joinPoint.proceed();

        Object repeatFlag = HelperUtil.getHttpServletRequest().getAttribute(IdempotentConst.REQUEST_REPEAT);

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Idempotent idempotent = method.getAnnotation(Idempotent.class);

        if (repeatFlag != null && (int) repeatFlag == 1) {
            throw new ServiceException(idempotent.msg());
        }

        return proceed;
    }

    @After(value = "pointcut()")
    public void doAfter(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        Idempotent idempotent = method.getAnnotation(Idempotent.class);
        String cacheKey = this.setCacheKey(idempotent, joinPoint, IdempotentConst.CACHE_TOKEN_PREFIX);

        if (idempotent.delKey()) {
            // 删除key，主要回收内存，感觉意义不大
            stringRedisTemplate.delete(cacheKey);
        }
    }

    private String setCacheKey(Idempotent idempotent, JoinPoint joinPoint, String prefix) {
        HttpServletRequest request = HelperUtil.getHttpServletRequest();

        String ip = IpUtil.getIpAddress();
        String uri = request.getRequestURI();

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        String args;
        if (StrUtil.isBlank(idempotent.key())) {
            // 没有配置幂等标识 key ，使用请求IP + URL + 请求方法 + 参数列表区分
            args = Arrays.asList(joinPoint.getArgs()).toString();
        }else {
            // 使用 jstl 表达式规则区分
            args = keyResolver.resolver(idempotent, joinPoint);
        }

        return StrUtil.join(":", prefix, ip, uri, method.getName(), args);
    }
}
